﻿Imports System.IO
Partial Class Extras_encriptarconection
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'On the first page visit, call DisplayWebConfig method
        If Not Page.IsPostBack Then
            DisplayWebConfig()
        End If
    End Sub

    Private Sub DisplayWebConfig()
        'Reads in the contents of Web.config and displays them in the TextBox
        Dim webConfigStream As StreamReader = File.OpenText(Path.Combine(Request.PhysicalApplicationPath, "Web.config"))
        Dim configContents As String = webConfigStream.ReadToEnd()
        webConfigStream.Close()

        WebConfigContents.Text = configContents
    End Sub

    Protected Sub EncryptConnStrings_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles EncryptConnStrings.Click
        'Get configuration information about Web.config
        Dim config As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)

        ' Let's work with the <connectionStrings> section
        Dim connectionStrings As ConfigurationSection = config.GetSection("connectionStrings")
        If connectionStrings IsNot Nothing Then
            ' Only encrypt the section if it is not already protected
            If Not connectionStrings.SectionInformation.IsProtected Then
                ' Encrypt the <connectionStrings> section using the DataProtectionConfigurationProvider provider
                connectionStrings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
                config.Save()

                ' Refresh the Web.config display
                DisplayWebConfig()
            End If
        End If
    End Sub

    Protected Sub DecryptConnStrings_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DecryptConnStrings.Click
        ' Get configuration information about Web.config
        Dim config As Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)

        ' Let's work with the <connectionStrings> section
        Dim connectionStrings As ConfigurationSection = config.GetSection("connectionStrings")
        If connectionStrings IsNot Nothing Then
            ' Only decrypt the section if it is protected
            If connectionStrings.SectionInformation.IsProtected Then
                ' Decrypt the <connectionStrings> section
                connectionStrings.SectionInformation.UnprotectSection()
                config.Save()

                ' Refresh the Web.config display
                DisplayWebConfig()
            End If
        End If
    End Sub
End Class
